<?php

// +----------------------------------------------------------------------
// | 私信
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------

namespace app\event\im;

use app\model\cms\Document;
use app\common\event\Base;
use app\model\im\Robot as RobotModel;
use app\event\im\Chat as ChatEvent;
use app\model\im\Chat as ChatModel;
use app\model\im\ChatContent as ChatContentModel;
use app\model\ucenter\User as UserModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;

class Robot extends Base
{


    public static function talk($chat, $scene = 'bind_id', $say = null, $robot_id = null, $from = 0)
    {
        try {

            $says = [];
            switch ($scene) {
                case 'bind_id':
                    // 获取迎宾机器人
                    $robot = RobotModel::where('store_app_id', $chat['store_app_id'])
                        ->where('status', 1)->where('type', 2)->find();
                    if (!$robot) {
                        throw new Exception('机器人不存在');
                    }
                    $says[] = self::_buildContent($robot, $chat, $say);
                    break;
                case 'single_chat':
                    if (is_null($robot_id)) {
                        // 自动回复
                        $autoKeyword = self::_autoKeyword($chat, $say);
                        if (empty($autoKeyword))
                        {
                            $content = null;
                            $robot = RobotModel::where('store_app_id', $chat['store_app_id'])
                                ->where('status', 1)->where('type', 99)->find();
                            if ($say['content'] == '人工服务') {
                                $event = new ChatEvent();
                                $params = [
                                    'chat_id' => $say['to_chat_id'],
                                ];
                                $re = $event->switchCustomer($params);
                                if ($re['code'] == 0) {
                                    $says[] = self::_buildContent($robot, $chat, $say, $re['message']);
//                                    $says[] = self::_buildContent($robot, $chat, $say, '转接成功...',5);
                                } else {
                                    $content = '转接失败：' . $re['message'];
                                }
                            } else {
                                //订单查询
                                $autoRobot = RobotModel::where('store_app_id', $chat['store_app_id'])->where('status', 1)->where('type', 11)->find();
                                if ($autoRobot) {
                                    // 第三方调用
                                    $says[] = self::_buildContent($autoRobot, $chat, $say,'',0,$autoRobot['id']);
                                } else {
                                    $content = '暂时不能回复，如需帮助,请回复“<a href="javascript:void(0);" onclick="sendChatData(\'人工服务\',\'text\')">【人工服务】</a>”';
                                }
                                //人工坐席忙，如需查询订单信息，,请回复{$订单查询}“<a href="javascript:void(0);" onclick="sendChatData(\'订单查询\',\'text\')">【订单查询】</a>”
//                    $content = '暂时不能回复，如需帮助,请回复“<a href="javascript:void(0);" onclick="sendChatData(\'人工服务\',\'text\')">【人工服务】</a>”';
                            }
                            $says[] = $autoKeyword;
                            if (!empty($content)) {
                                $says[] = self::_buildContent($robot, $chat, $say, $content);
                            }
                        }else{
                            $says[] = $autoKeyword;
                        }
                    } else {
                        // 指定机器人
                        $robot = RobotModel::where('status', 1)->where('id', $robot_id)->find();

                        if ($robot) {
                            $says[] = self::_buildContent($robot, $chat, $say, '查询成功单号：'.$say['content']);
                        }
                    }

                    break;
                case 'auto_say':
                    /**
                     * 客服无应答时消息    客服一段时间没有响应顾客消息时，系统自动向他发送一段消息    3
                     * 顾客无响应时消息    顾客一段时间没有响应客服消息时，系统自动向他发送一段消息    4
                     * 客服手动结束时    对话结束后，系统自动向顾客发送一段结束语    6
                     * 系统自动结束时    对话结束后，系统自动向顾客发送一段结束语    5
                     */
                    $robot = RobotModel::where('status', 1)->where('id', $robot_id)->find();
                    if ($robot) {
                        $says[] = self::_buildContent($robot, $chat);
                    }
                    if ($robot['type'] == 5) {
                        // 关闭聊天
                        ChatEvent::systemCloseChat($chat);
                    }
                    break;

                default:
                    throw new Exception('未知场景');
            }
            $data['code'] = 0;
            $data['data'] = $says;
            $data['message'] = '发送成功';
        } catch (\Exception $e) {
            $data['code'] = 2;
            $data['message'] = 'file:' . $e->getFile() . ',message:' . $e->getMessage() . 'li' . $e->getLine();
//				$data['message'] = $e->getMessage();
        }
        return $data;
    }

    /**
     * 关键词自动回复
     * @param  $chat_content
     * @param UserModel $user
     */
    protected static function _autoKeyword($chat, $say, $service = null, $from = 0): array
    {
        $content = null;
        //获取关联知识库
        $robot = RobotModel::where('store_app_id', $chat['store_app_id'])->where('status', 1)->where('type', 1)->find();
        if ($robot) {
            $content = self::_buildContent($robot, $chat, $say);
        }
        if (empty($content)) {
            // 获取关键词机器人
            $robot = RobotModel::where('status', 1)
                ->where('store_id', $chat['store_id'])
                ->when(is_null($service), function ($query) {
                    // 满足条件后执行
                    $query->where('is_common', 1);
                }, function ($query) use ($service) {
                    // 不满足条件执行
                    $query->where('user_id', $service['id'])->where('is_common', 0);
                })
                ->where('type', 7)
                ->order('sort', 'desc')
                ->whereRaw('(`keyword` = \'' . $say['content'] . '\' AND `match_type` = 1) OR (`keyword` LIKE \'%' . $say['content'] . '%\' AND `match_type` = 0)')
                ->find();
            if ($robot) {
                $content = self::_buildContent($robot, $chat, $say);
            }
        }
        return $content;
    }

    /**
     * 自动回复欢迎
     * @param  $chat_content
     * @param UserModel $user
     */
    public static function autoHello($chat, UserModel $user, UserModel $service = null, $from = 0)
    {
        try {
            $robot = RobotModel::where('store_id', $user['store_id'])->where('status', 1)->where('type', 2)->find();
            if (!$robot) {
                throw new Exception('未开启欢迎语');
            }
            $data['code'] = 0;
            $data['data'] = self::_buildContent($robot, $chat);
            $data['message'] = '发送成功';
        } catch (\Exception $e) {
            $data['code'] = 2;
            $data['message'] = 'file:' . $e->getFile() . ',message:' . $e->getMessage() . 'li' . $e->getLine();
//				$data['message'] = $e->getMessage();
        }
        return $data;
    }

//
//    /**
//     * 自动回复
//     * @param  $chat_content
//     * @param UserModel $user
//     */
//    public static function auto($chat_content, UserModel $user, UserModel $service = null, $from = 0)
//    {
//        try {
////				Db::startTrans();
//
////        // 获取配置关键词机器人
//            $robot = RobotModel::where('store_id', $user['store_id'])->where('status', 1)->where('type', 7)->find();
//            if (!$robot) {
//                throw new Exception('机器人不存在');
//            }
//            $content = '';
//            if ($chat_content['type'] == 'text') {
//                ///查询匹配知识库
//                $doc = Document::where('status', 1)->where('title', $chat_content['content'])
//                    ->where('user_id', $user['store_id'])
//                    ->where('category_id', 9)
//                    ->find();
//                if ($doc) {
//                    $content = $doc['article']['content'];
//                } else {
//                    // 查询客服独享
//                    $robot = RobotModel::where('status', 1)
//                        ->where('store_id', $user['store_id'])
//                        ->where('user_id', $service['id'])
//                        ->where('is_common', 0)
//                        ->order('sort', 'desc')
//                        ->whereRaw('(`keyword` = \'' . $chat_content['content'] . '\' AND `match_type` = 1) OR (`keyword` LIKE \'%' . $chat_content['content'] . '%\' AND `match_type` = 0)')
//                        ->find();
//                    if (!$robot) {
//                        // 共享查询
//                        $robot = RobotModel::where('status', 1)
//                            ->where('store_id', $user['store_id'])
//                            ->where('is_common', 1)
//                            ->order('sort', 'desc')
//                            ->whereRaw('(`keyword` = \'' . $chat_content['content'] . '\' AND `match_type` = 1) OR (`keyword` LIKE \'%' . $chat_content['content'] . '%\' AND `match_type` = 0)')
//                            ->find();
//                    }
//                    if ($robot) {
//                        if ($robot['type'] == 0) {
//                            $content = $robot['reply'];
//                        } elseif ($robot['type'] == 1) {
//                            $doc = Document::where('status', 1)
//                                ->where('id', $robot['document_id'])
//                                ->find();
//                            if ($doc) {
//                                $content = $doc['article']['content'];
//                            }
//                        }
//                        $robot['match_number'] = $robot['match_number'] + 1;
//                        $robot->save();
//                    }
//                }
//            }
//
//            $ai = UserModel::where('id', $user['store']['ai_user_id'])->field('id,nickname,avatar_id,avatar_url')->find()->toArray();
//
//            if (empty($content)) {
//                throw new Exception('没有匹配到合适的回复');
//            }
////				Db::commit();
//            $data['code'] = 0;
//            $data['data'] = [
//                'type' => 'text',
//                'ip' => '0.0.0.0',
//                'from_chat_id' => isset($chat_content['from_chat_id']) ? $chat_content['from_chat_id'] : 0,
//                'delay' => $robot ? $robot['delay'] : 0,
//                'ref' => build_encrypt_key(),
//                'content' => $content,
//                'create_time' => time_format(),
//                'user' => $ai];;
//            $data['message'] = '发送成功';
//        } catch (\Exception $e) {
//            // 回滚事务
//            Db::rollback();
//            $data['code'] = 2;
//            $data['message'] = 'file:' . $e->getFile() . ',message:' . $e->getMessage() . 'li' . $e->getLine();
////				$data['message'] = $e->getMessage();
//        }
//        return $data;
//    }

    /**
     * 营销机器人
     * @param  $chat_content
     * @param UserModel $user
     */
    public static function ai($chat, $say, UserModel $user, $robot_id = null, $scene = 'bind_id', $from = 0)
    {
        try {
            $robot = RobotModel::where('store_id', $user['store_id'])->where('status', 1)->where('id', $robot_id)->find();
            if ($robot && $robot['type'] == 11) {
                //::TODO 对接查询
                // 获取营销机器人
                $robot = RobotModel::where('store_id', $user['store_id'])->where('status', 1)->where('type', 20)->find();
                if (!$robot) {
                    throw new Exception('机器人不存在');
                }
                $content = '暂未查询到更新信息，更多功能请回复“<a href="javascript:void(0);" onclick="sendChatData(\'人工服务\',\'text\')">【人工服务】</a>”';
            } else {
                // 获取营销机器人
                $robot = RobotModel::where('store_id', $user['store_id'])->where('status', 1)->where('type', 20)->find();
                if (!$robot) {
                    throw new Exception('机器人不存在');
                }
                if ($scene == 'bind_id') {
                    $data['data'] = self::_buildContent($robot, $chat, $say);
                } elseif ($scene == 'chat') {
                    if ($say['content'] == '人工服务') {
                        $event = new ChatEvent();
                        $params = [
                            'chat_id' => $say['to_chat_id'],
                        ];
                        $re = $event->switchCustomer($params);
                        if ($re['code'] == 0) {
                            $content = '正在转接人工服务...';
                        } else {
                            $content = '转接失败：' . $re['message'];
                        }
                    } else {

                        $autoRobot = RobotModel::where('store_id', $user['store_id'])->where('status', 1)->where('type', 11)->find();
                        if ($autoRobot) {
                            // 第三方调用
                            $data['data'] = self::_buildContent($autoRobot, $chat, $say,'',0,0,$autoRobot['id']);
                        } else {
                            $content = '暂时不能回复，如需帮助,请回复“<a href="javascript:void(0);" onclick="sendChatData(\'人工服务\',\'text\')">【人工服务】</a>”';
                        }

                        //人工坐席忙，如需查询订单信息，,请回复{$订单查询}“<a href="javascript:void(0);" onclick="sendChatData(\'订单查询\',\'text\')">【订单查询】</a>”
//                    $content = '暂时不能回复，如需帮助,请回复“<a href="javascript:void(0);" onclick="sendChatData(\'人工服务\',\'text\')">【人工服务】</a>”';
                    }
                }
            }

            if (!empty($content)) {
                $data['data'] = self::_buildContent($robot, $chat, $say, $content);
            }
            $data['code'] = 0;
            $data['message'] = '发送成功';
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $data['code'] = 2;
            $data['message'] = 'file:' . $e->getFile() . ',message:' . $e->getMessage() . 'li' . $e->getLine();
//				$data['message'] = $e->getMessage();
        }
        return $data;
    }

    /**
     * 生成返回内容
     * @param $robot
     * @param string $content
     * @param $say
     * @return array
     * @throws Exception
     */
    protected static function _buildContent($robot, $chat, $say = null, string $content = '',$delay=0,$bind_robot_id=null): array
    {
        $ai = UserModel::where('id', $robot['app']['ai_user_id'])->field('id,nickname,avatar_id,avatar_url')->find();
        if (!$content) {
            if ($robot['type'] == 1) {
                // 关联知识库
                $doc = Document::where('status', 1)->where('title', $say['content'])
                    ->where('user_id', $robot['store_id'])
                    ->where('category_id', 9)
                    ->find();
                if ($doc) {
                    $content = $doc['article']['content'];
                }
            } else {
                if ($robot['content_type'] == 1) {
                    $doc = Document::where('status', 1)->where('id', $robot['document_id'])
                        ->find();
                    if ($doc) {
                        $content = $doc['article']['content'];
                    }
                } elseif ($robot['content_type'] == 0) {
                    // 默认回复
                    $content = $robot['reply'];
                } else {
                    throw new Exception('类型不支持');
                }
            }
        }

        if (empty($content)) {
            return [];
        }
        $robot['match_number'] = $robot['match_number'] + 1;
        $robot->save();
        if (strpos($content, '{$') !== false) {
            $pattern = '/\{\$+([\x{4e00}-\x{9fa5}|[0-9a-zA-Z]{1,20})+\}/u';
            preg_match_all($pattern, $content, $matches);
            if (!empty($matches)) {
                foreach ($matches[0] as $key => $match) {
                    $tpl = '<a href="javascript:void(0);" onclick="sendChatData(\'' . $matches[1][$key] . '\',\'text\')">【' . $matches[1][$key] . '】</a>';
                    $content = str_replace($match, $tpl, $content);
                }
            }
        }

        return [
            'type' => 'text',
            'ip' => '0.0.0.0',
            'bind_robot_id' => $bind_robot_id,
            'to_chat_id' => $chat['id'],
            'robot_id' => $robot['id'],
            'delay' => $delay>0?$delay:$robot['delay'],
            'guid' => build_encrypt_key(),
            'content' => $content,
            'create_time' => time_format(),
            'user' => $ai
        ];
    }

    /**
     * 智能回复
     * @param  $chat_content
     * @param UserModel $user
     */
//    public static function exact($chat_content, UserModel $user, UserModel $service = null, $from = 0)
//    {
//        try {
////				Db::startTrans();
//            // ai机器人欢迎语
//            $ai = UserModel::where('id', $user['store']['ai_user_id'])->field('id,nickname,avatar_id,avatar_url')->find()->toArray();
//            $content = '';
//            if ($chat_content['type'] == 'text') {
//                ///查询匹配知识库
//                $doc = Document::where('status', 1)->where('title', $chat_content['content'])
//                    ->where('user_id', $service['store_id'])
//                    ->where('category_id', 9)
//                    ->find();
//                if ($doc) {
//                    $content = $doc['article']['content'];
//                } else {
//                    // 查询客服独享
//                    $robot = RobotModel::where('status', 1)
//                        ->where('store_id', $service['store_id'])
//                        ->where('user_id', $service['id'])
//                        ->where('is_common', 0)
//                        ->order('sort', 'desc')
//                        ->whereRaw('(`keyword` = \'' . $chat_content['content'] . '\' AND `match_type` = 1) OR (`keyword` LIKE \'%' . $chat_content['content'] . '%\' AND `match_type` = 0)')
//                        ->find();
//                    if (!$robot) {
//                        // 共享查询
//                        $robot = RobotModel::where('status', 1)
//                            ->where('store_id', $service['store_id'])
//                            ->where('is_common', 1)
//                            ->order('sort', 'desc')
//                            ->whereRaw('(`keyword` = \'' . $chat_content['content'] . '\' AND `match_type` = 1) OR (`keyword` LIKE \'%' . $chat_content['content'] . '%\' AND `match_type` = 0)')
//                            ->find();
//                    }
//                    if ($robot) {
//
//                        if ($robot['type'] == 0) {
//                            $content = $robot['reply'];
//                        } elseif ($robot['type'] == 1) {
//                            $doc = Document::where('status', 1)
//                                ->where('id', $robot['document_id'])
//                                ->find();
//                            if ($doc) {
//                                $content = $doc['article']['content'];
//                            }
//                        }
//                        $robot['match_number'] = $robot['match_number'] + 1;
//                        $robot->save();
//                    }
//                }
//            }
//            if (empty($content)) {
//                throw new Exception('没有匹配到合适的回复');
//            }
////				Db::commit();
//            $data['code'] = 0;
//            $data['data'] = [
//                'type' => 'text',
//                'ip' => '0.0.0.0',
//                'from_chat_id' => $chat_content['from_chat_id'],
//                'delay' => $chat_content['delay'],
//                'guid' => build_encrypt_key(),
//                'content' => $content,
//                'create_time' => time_format(),
//                'user' => $ai];;
//            $data['message'] = '发送成功';
//        } catch (\Exception $e) {
//            // 回滚事务
//            Db::rollback();
//            $data['code'] = 2;
//            $data['message'] = 'file:' . $e->getFile() . ',message:' . $e->getMessage() . 'li' . $e->getLine();
////				$data['message'] = $e->getMessage();
//        }
//        return $data;
//    }

}
